<?php
class Model_Photo extends Df_Model
{

    private $user_name;

    private $album_id;

    public function __construct ($user_name = null, $id = null) {
        $this->user_name = $user_name;
        $this->album_id = $id;
        parent::__construct(new Model_DbTable_Photoalbum(), $id);
    }

    public function createAlbum ($album_id) {
        $album_name = 'album' . DIRECTORY_SEPARATOR . $this->user_name;
        mkdir($album_name, 0755);
        
        $album_name .= DIRECTORY_SEPARATOR . $album_id;
        mkdir($album_name, 0755);
        
        mkdir($album_name . DIRECTORY_SEPARATOR . 'thumb', 0700);
    }

    public function getUserAlbumList ($user_id) {
        return $this->_dbTable->fetchAll(
        $this->_dbTable->select()
            ->where('user_id = ?', $user_id));
    }

    public function getPhotosList ($album_id) {
        $results = array();
        
        $album_id = 'album' . DIRECTORY_SEPARATOR . $this->user_name .
         DIRECTORY_SEPARATOR . $album_id;
        
        $handler = opendir($album_id);
        
        while ($file = readdir($handler)) {
            
            // if file isn't this directory or its parent, add it to the results
            if ($file != "." && $file != ".." && $file != "thumb") {
                $results[] = $file;
            }
        
        }
        closedir($handler);
        
        return $results;
    }

    public function removeAlbum () {
        //TODO check more parametrs to emove folder
        $album_name = 'album' . DIRECTORY_SEPARATOR . $this->user_name .
         DIRECTORY_SEPARATOR . $this->album_id;
        rmdir($album_name);
        
        //TODO remove from DB
        $this->_row->delete();
    
    }

    /** 
     * photos are stored in user name folder
     * */
    
    public function removePhoto ($album_id, $photo_name) {
        $photo = 'album' . DIRECTORY_SEPARATOR . $this->user_name .
         DIRECTORY_SEPARATOR . $album_id . DIRECTORY_SEPARATOR . $photo_name;
        unlink($photo);
    }
    
    public function getAlbumName($album_id){
      return $this->_dbTable->fetchRow(
			$this->_dbTable->select()
				->where('id = ?',$album_id)
			);
    }

}